package suncertify.controller;

import java.io.IOException;
import java.io.Serializable;
import java.util.Vector;

import suncertify.db.Data;
import suncertify.db.RecordNotFoundException;
import suncertify.db.Room;
import suncertify.network.ServerHelper;
import suncertify.network.ServerInterface;
import suncertify.resources.App;

/**
 * Manages the user actions coming from the <code>SearchController</code> class.
 * @author Paul Wilhelm
 *
 */
public class SearchController implements Serializable {
	private static final long serialVersionUID = 1981;			//Verifies the class during deserialization
	private ServerInterface data;								//The data object to be used

	/**
	 * Constructor.  Creates a new <code>SearchController</code> object and assigns the data object
	 * depending on whether the user is running in networked or alone mode.
	 */
	public SearchController() {
		if (App.isNetworked){			//If in networked mode, use the remote DB
			data = ServerHelper.getRemoteDatabase();
		}
		if (App.isAlone){				//If in alone mode, use the local DB file
			data = Data.getInstance();
		}
	}
	
	/**
	 * Searches for rooms with the specified criteria.  Places the results in a Vector.
	 * @param name - The name of the hotel to search for
	 * @param location - The location of the hotel to search for
	 * @return A Vector holding all the matching data.
	 * @throws IOException
	 * @throws RecordNotFoundException
	 */
	public Vector<Room> searchBtnClick(String name, String location) throws IOException, RecordNotFoundException{
		Vector<Room> results = new Vector<Room>();
		String[] criteria = {name, location};
		if (name.equals("") && location.equals("")){			//If no criteria was entered
				return data.getAllRooms();
		}
		else {													//If criteria was entered
			int[] findResults = data.find(criteria);
			for (int i = 0; i < findResults.length; i++){		//For each element in the array returned from the data.find() method, create a room object
				String[] roomArray = data.read(findResults[i]);
				Room room = new Room(roomArray[0], roomArray[1], roomArray[2], roomArray[3], roomArray[4], roomArray[5], roomArray[6]);
				results.add(room);
			}
		}
		if (results.isEmpty()){			//If no record is found
			throw new RecordNotFoundException();
		}
		return results;
	}

}
